<template>
  <div>
    <div v-if="$route.query.type==='applyAudit'" style="padding-bottom:10px">
      <!-- <el-button size="mini" type="primary" @click.native="handleEdit">编辑</el-button> -->
      <el-button v-if="patrolId" size="mini" type="primary" @click.native="handleEditBatch">一键无需整改</el-button>
      <el-button v-if="patrolId" size="mini" type="primary" @click.native="handleEditItem">撤销无需整改</el-button>
      <el-button size="mini" type="primary" @click.native="deleteBatch">删除</el-button>
      <!-- <el-button size="mini" type="primary" @click.native="handleTableSave">保存</el-button> -->
      <el-button size="mini" type="primary" @click.native="handlequeryData">刷新</el-button>
    </div>
    <div v-else style="padding-bottom:10px">
      <div v-if="!isDetail">
        <el-button size="mini" type="primary" @click.native="handleAdd">新增</el-button>
        <el-button size="mini" type="primary" @click.native="handleEdit">编辑</el-button>
        <!-- <el-button size="mini" type="primary" @click.native="handleTableSave">保存</el-button> -->
        <el-button size="mini" type="primary" @click.native="deleteBatch">删除</el-button>
        <el-button size="mini" type="primary" @click.native="handlequeryData">刷新</el-button>

      </div>
    </div>
    <el-table
      :data="tableData"
      border
      max-height="300"
      :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
      style="width: 100%"
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="50"
      />
      <el-table-column show-overflow-tooltip prop="floorCode" label="巡检楼层">
        <template slot-scope="scope">
          <c-dict-select v-model="scope.row.floorCode " disabled dict-type-code="FLOOR" />
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="areaName" label="图纸区域" />
      <el-table-column prop="surface" label="巡检立面" />
      <el-table-column width="110px" show-overflow-tooltip prop="dutyId" label="责任归属">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.dutyId"
            disabled
            @change="()=>scope.row.acceptProblemId=''"
          >
            <el-option
              v-for="item in dutyTypeList"
              :key="item.id"
              :label="item.belongDuty"
              :value="item.id"
            />
          </el-select>
          <!-- <c-dict-select v-model="scope.row.dutyId " :disabled="!scope.row.isEdit" dict-type-code="BELONG_DUTY" /> -->
        </template>
      </el-table-column>
      <el-table-column width="110px" show-overflow-tooltip prop="acceptProblemId" label="问题分类">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.acceptProblemId"
            disabled
          >
            <el-option
              v-for="item in acceptProblemList"
              v-show="scope.row.dutyId===item.configAcceptDutyId"
              :key="item.id"
              :label="item.problemClass"
              :value="item.id"
            />
          </el-select>
          <!-- <c-dict-select v-model="scope.row.acceptProblemId "
           :disabled="!scope.row.isEdit&&!scope.row.dutyId" dict-type-code="PROBLEM_CATEGORY" /> -->
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="problemDesc" label="问题描述" />
      <el-table-column label="整改前">
        <template slot-scope="scope">
          <import-img
            readonly
            :photo-list="scope.row.fileList1"
            file-type="巡检问题(前)"
            :config-attachment-id="configIdBefore"
          />
        </template>
      </el-table-column>
      <el-table-column label="整改后">
        <template slot-scope="scope">
          <import-img
            readonly
            :photo-list="scope.row.fileList2"
            file-type="巡检问题(后)"
            :other-param="scope.$index"
            :config-attachment-id="configIdAfter"
            @upload-success="changeTableStatus"
            @remove="changeTableStatus"
          />
        </template>
      </el-table-column>

      <el-table-column width="120" prop="status" label="整改情况">
        <template slot-scope="scope">
          <c-dict-select v-model="scope.row.status" disabled dict-type-code="RECTIFICATION_SITUATION" />
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="specialNo" label="特殊流程编号" />

    </el-table>
    <el-dialog
      v-if="dlgVisible"
      ref="refDlg"
      :visible.sync="dlgVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="closeDialog"
      width="600px"
      :title="editForm.id?'编辑':'新增'"
      @close="closeDialog"
    >
      <el-form ref="refForm" :rules="editRules" :model="editForm" size="mini" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="走访楼层:" prop="floorCode">
              <c-dict-select v-model="editForm.floorCode " dict-type-code="FLOOR" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图纸区域:" prop="areaCode">
              <input-with-dialog
                v-model="areaArr"
                :props="{label:'areaName',value:'areaCode'}"
                :config="{
                  title:'区域',
                  width:'600px',
                  interfacePath:`/slm-admin/api/v1/configArea/page`,
                  method:'post',
                  filtersRaw:[{'property':'enable','value':'1','operator':'=','id':'enable'}],
                  paramsRaw:{},
                  setting:[
                    {prop:'areaCode',title:'编码'},
                    {prop:'areaName',title:'名称'}
                  ]
                }"
                @change="changeArea"
              >
                <!-- <c-remote-select
                placeholder="请选择"
                url="/api/v1/configArea/page"
                method="POST"
                :value="editForm.areaCode"
                value-name="areaCode"
                label-name="areaName"
                :filters-raw="[{ key: 'enable', value: '1', operator: '=' } ]"
                @input="data=>{editForm.areaCode=data;editForm.areaName=data}"
              /> -->
              </input-with-dialog></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="巡检立面:" prop="surface">
              <el-input-number
                v-model="editForm.surface"
                size="mini"
                :min="1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="责任归属:" prop="dutyId">
              <el-select
                v-model="editForm.dutyId"
                @change="()=>editForm.acceptProblemId=''"
              >
                <el-option
                  v-for="item in dutyTypeList"
                  :key="item.id"
                  :label="item.belongDuty"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="问题分类:" prop="acceptProblemId">
              <el-select
                v-model="editForm.acceptProblemId"
              >
                <el-option
                  v-for="item in acceptProblemList"
                  v-show="editForm.dutyId===item.configAcceptDutyId"
                  :key="item.id"
                  :label="item.problemClass"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <!-- 待整改 可以将未整改修改为无法整改，备注必填 -->
            <el-form-item :rules="[{ required:editForm.status==='C', message: '请填写', trigger: 'change' }]" label="问题描述:" prop="problemDesc">
              <el-input v-model="editForm.problemDesc" type="textarea" size="mini" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="整改前:" prop="fileList1">
              <import-img
                :photo-list="editForm.fileList1"
                file-type="巡检问题(前)"
                :config-attachment-id="configIdBefore"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="整改后:" prop="">
              <import-img
                :photo-list="editForm.fileList2"
                file-type="巡检问题(后)"
                :config-attachment-id="configIdAfter"
                @upload-success="changeStatus"
                @remove="changeStatus"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="整改情况:" prop="status">
              <el-select
                v-model="editForm.status"
                placeholder="请选择"
                :disabled="schedule!=='B'&&schedule!=='C'"
                style="width: 100%"
              >

                <el-option
                  v-for="item in filterOption()"
                  :key="item.dictCode"
                  :disabled="!item.canSelect"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="整改情况:" prop="status">
              <c-dict-select v-model="editForm.status" :disabled="schedule!=='B'" dict-type-code="RECTIFICATION_SITUATION" />
            </el-form-item> -->
          </el-col>
          <el-col :span="12">
            <el-form-item label="特殊流程编号:" prop="specialNo">
              <el-input v-model="editForm.specialNo" size="mini" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button :loading="saveLoading" size="mini" type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>
<script>
import { getDictByPatchType } from '@/api/dataDict'
import importImg from '@/components/importImg/miniUpload'
import { deepClone } from '@/utils'
import { queryProblemList, saveProblem, problemDeleteBatch, queryDutyList, queryProblemClassList } from '@/api/marketService/decorateInspection'
export default {
  name: 'ProblemInfo',
  components: { importImg },
  props: {
    patrolId: {
      type: String,
      default: ''
    },
    schedule: {
      type: String,
      default: ''
    },
    configIdBefore: {
      type: String,
      default: ''
    },
    model: {
      type: String,
      default: ''
    },
    configIdAfter: {
      type: String,
      default: ''
    }

  },
  data() {
    return {
      saveLoading: false,
      isDetail: 0,
      statusOptions: [],
      areaArr: [],
      editRules: {
        floorCode: [{ required: true, message: '请选择', trigger: 'change' }],
        areaCode: [{ required: true, message: '请选择', trigger: 'change' }],
        acceptProblemId: [{ required: true, message: '请选择', trigger: 'change' }],
        dutyId: [{ required: true, message: '请选择', trigger: 'change' }],
        fileList1: [{ required: true, type: 'array', message: '请上传', trigger: 'change' }]
      },
      dutyTypeList: [],
      editForm: {},
      dlgVisible: false,
      tableSelected: [],
      acceptProblemList: [],
      issueIds: [],
      tableData: []
    }
  },
  watch: {
    patrolId: {
      handler(v) {
        if (!v) return
        this.handlequeryData()
      },
      deep: true,
      immediate: true
    }
  },
  async created() {
    const { isDetail } = this.$route.query
    this.isDetail = isDetail
    queryDutyList().then(res => {
      if (res.success) {
        this.dutyTypeList = res.data.records || []
        queryProblemClassList().then(res => {
          if (res.success) this.acceptProblemList = res.data.records || []
        })
      }
    })
    const { RECTIFICATION_SITUATION } = await getDictByPatchType(['RECTIFICATION_SITUATION'])
    this.statusOptions = RECTIFICATION_SITUATION
  },
  methods: {
    // 问题待审核B 可以将未整改A修改为无需整改E，无需整改修改为未整改
    // 待整改C 可以将未整改A修改为无法整改C，备注必填；
    filterOption() {
      console.log(this.schedule)
      if (this.schedule === 'B') {
        return this.statusOptions.map(v => {
          if (v.dictCode === 'A' || v.dictCode === 'E') return { ...v, canSelect: true }
          else return { ...v, canSelect: false }
        })
      } else if (this.schedule === 'C') {
        return this.statusOptions.map(v => {
          if (v.dictCode === 'A' || v.dictCode === 'C') return { ...v, canSelect: true }
          else return { ...v, canSelect: false }
        })
      } else {
        return this.statusOptions
      }
    },
    changeArea(data) {
      if (data && data.length) {
        this.$set(this.editForm, 'areaCode', data[0].areaCode)
        this.$set(this.editForm, 'areaName', data[0].areaName)
      } else {
        this.editForm.areaCode = ''
        this.editForm.areaName = ''
      }
    },
    changeStatus({ imgLength }) {
      //  （3）巡检任务进度为【待提交】A，上传整改后的图片时，整改情况默认为【现场已整改】D
      //  （4）巡检任务进度为【待整改】B，上传整改后的图片时，整改情况默认为【已整改】B
      //  （4）巡检任务进度为【待整改】C，上传整改后的图片时，整改情况默认为【已整改】B
      if (this.schedule === 'A') {
        if (imgLength > 0) {
          this.$set(this.editForm, 'status', 'D')
        } else {
          this.$set(this.editForm, 'status', 'A')
        }
      } else if (this.schedule === 'C' || this.schedule === 'B') {
        if (imgLength > 0) {
          this.$set(this.editForm, 'status', 'B')
        } else {
          this.$set(this.editForm, 'status', 'A')
        }
      } else {
        this.$set(this.editForm, 'status', 'A')
      }
    },
    changeTableStatus({ imgLength, otherParam }) {
      //  （3）巡检任务进度为【待提交】A，上传整改后的图片时，整改情况默认为【现场已整改】D
      //  （4）巡检任务进度为【待整改】C，上传整改后的图片时，整改情况默认为【已整改】B
      if (this.schedule === 'A') {
        if (imgLength > 0) {
          this.$set(this.tableData[otherParam], 'status', 'D')
        } else {
          this.$set(this.tableData[otherParam], 'status', 'A')
        }
      } else if (this.schedule === 'C') {
        if (imgLength > 0) {
          this.$set(this.tableData[otherParam], 'status', 'B')
        } else {
          this.$set(this.tableData[otherParam], 'status', 'A')
        }
      } else {
        this.$set(this.tableData[otherParam], 'status', 'A')
      }
    },
    deleteBatch() {
      if (!this.singleJudge(this.tableSelected, '删除', false)) {
        return
      }
      const newAddList = this.tableSelected.filter(v => !v.id)
      const oldList = this.tableSelected.filter(v => v.id)
      if (newAddList.length) { // 删除新建数据
        const flag = this.tableData.filter(item => {
          const index = newAddList.findIndex(i => i.addFlag === item.addFlag)
          return index === -1
        })
        this.tableData = flag
      }
      if (oldList.length) { // 删除已保存数据
        problemDeleteBatch(oldList.map(v => v.id)).then(res => {
          if (res.success) {
            this.$message.success('操作成功')
            this.handlequeryData()
          }
        })
      }
    },
    getIds(type) { // type为1表示提交，路由的type2代表校验整改状态
      if (type && this.$route.query.type === '2' && this.tableData.filter(v => v.status === 'A').length) return
      else return [...this.tableData.filter(i => i.id).map(v => v.id), ...this.issueIds]
    },
    handleSave() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          this.editForm.shopAttachmentDTOList = [
            ... this.editForm.fileList1,
            ... this.editForm.fileList2
          ]
          this.saveLoading = true
          saveProblem(this.editForm).then(res => {
            if (res.success) {
              if (this.patrolId) this.handlequeryData()
              else {
                const keyindex = this.tableData.findIndex(v => v.id && v.id === res.data)// 判断原表格是否有此条问题
                keyindex !== -1 ? this.tableData[keyindex] = { ...this.editForm, id: res.data } : this.tableData.push({ ...this.editForm, id: res.data })
              }
              this.closeDialog()
              this.$message.success('保存成功')
            }
            this.saveLoading = false
          }).catch(() => {
            this.saveLoading = false
          })
        }
      })
    },
    handleTableSave() {
      if (!this.singleJudge(this.tableSelected, '保存', true)) {
        return
      }
      if (!this.tableSelected[0].fileList1 || this.tableSelected[0].fileList1.length === 0) {
        this.$message.warning('请上传整改前图片')
        return
      }
      this.tableSelected[0].shopAttachmentDTOList = [
        ... this.tableSelected[0].fileList1,
        ... this.tableSelected[0].fileList2
      ]
      saveProblem(this.tableSelected[0]).then(res => {
        if (res.success) {
          this.$message.success('保存成功')
          if (!this.patrolId) this.issueIds.push(res.data)
        }
      })
    },
    handleAdd() {
      let item
      if (this.tableData.length) {
        const { acceptProblemId, areaCode, areaName, dutyId, floorCode, patrolId, surface,
          shopAttachmentDTOList } = this.tableData[this.tableData.length - 1]
        this.areaArr = [{ label: areaName, value: areaCode }]
        // const file1 = fileList1.map(v => { return { ...v, modelId: '', id: null } })// todo生成附件id
        // const file2 = fileList2.map(v => { return { ...v, modelId: '', id: null } })
        item = { addFlag: Math.floor(Math.random() * 0xffffff).toString(16), acceptProblemId, areaCode, areaName, dutyId, surface,
          floorCode, patrolId, fileList1: [], fileList2: [], problemDesc: '',
          specialNo: '', status: 'A',
          shopAttachmentDTOList, isEdit: true }
      } else {
        item = {
          addFlag: Math.floor(Math.random() * 0xffffff).toString(16),
          acceptProblemId: '',
          acceptProblemName: '',
          fileList1: [],
          fileList2: [],
          areaCode: '',
          areaName: '',
          dutyId: '',
          dutyName: '',
          floorCode: '',
          floorName: '',
          isEdit: true,
          id: null,
          patrolId: this.patrolId,
          problemDesc: '',
          shopAttachmentDTOList: [],
          specialNo: '',
          status: 'A', // 默认新增未整改
          surface: undefined
        }
      }

      this.editForm = item
      this.dlgVisible = true
    },
    handleEditItem() {
      if (!this.singleJudge(this.tableSelected, '撤销', true)) {
        return
      }
      if (this.tableSelected[0].status === 'A') {
        this.$message.warning('当前状态已为未整改')
        return
      }
      this.saveLoading = true
      saveProblem({ ...this.tableSelected[0], status: 'A' }).then(res => {
        if (res.success) {
          if (this.patrolId) this.handlequeryData()
          this.$message.success('保存成功')
        }
        this.saveLoading = false
      }).catch(() => {
        this.saveLoading = false
      })
    },
    handleEdit() {
      if (!this.singleJudge(this.tableSelected, '编辑', true)) {
        return
      }
      this.editForm = deepClone(this.tableSelected[0])
      this.areaArr = [{ label: this.editForm.areaName, value: this.editForm.areaCode }]
      this.dlgVisible = true
    },
    closeDialog() {
      this.dlgVisible = false
      this.editForm = {}
      this.areaArr = []
    },
    // 一键无需整改
    handleEditBatch() {
      // const tempArr = this.tableData.filter(v => v.status)
    },
    handlequeryData() {
      if (!this.patrolId) return
      queryProblemList(this.patrolId).then(res => {
        if (res.success) {
          res.data.records.map(v => {
            this.$set(v, 'fileList1', (v.shopAttachmentDTOList || []).filter(v => v.configAttachmentId === this.configIdBefore))
            this.$set(v, 'fileList2', (v.shopAttachmentDTOList || []).filter(v => v.configAttachmentId === this.configIdAfter))
          })
          this.tableData = res.data.records
        }
      })
    },
    handleSelectionChange(rows) {
      this.tableSelected = rows
    },
    goBack() {

    },
    handlePreview() {

    }
  }
}
</script>
